package com.namecard.namecardapi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.mongodb.DuplicateKeyException;
import com.mongodb.MongoBulkWriteException;
import com.namecard.namecardapi.entity.Industry;
import com.namecard.namecardapi.service.IndustryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wjh
 * @create 2024-08-30 19:33
 */
@Slf4j
@Service
public class IndustryServiceImpl implements IndustryService {

    @Resource
    private MongoTemplate mongoTemplate;


    @Override
    public void batchInsertIndustry(List<Industry> industries) {
        // 收集所有待插入的行业名称
        List<String> industryNames = industries.stream()
                .map(Industry::getName)
                .collect(Collectors.toList());

        // 查询数据库中已存在的行业
        Query query = new Query(Criteria.where("name").in(industryNames));
        List<Industry> existingIndustries = mongoTemplate.find(query, Industry.class);

        // 创建一个 Map 以快速查找已存在的行业
        Map<String, Industry> existingIndustryMap = existingIndustries.stream()
                .collect(Collectors.toMap(Industry::getName, industry -> industry));

        // 处理需要更新的行业和新增的行业
        List<Industry> industriesToInsert = new ArrayList<>();
        for (Industry industry : industries) {
            Industry existingIndustry = existingIndustryMap.get(industry.getName());

            if (existingIndustry != null) {
                // 如果行业已存在，检查 positions 长度是否超过 1000
                if (existingIndustry.getPositions().size() < 1000) {
                    // 检查职位是否重复
                    Set<String> existingPositions = new HashSet<>(existingIndustry.getPositions());
                    List<String> positionsToAdd = industry.getPositions().stream()
                            .filter(position -> !existingPositions.contains(position))
                            .collect(Collectors.toList());

                    if (!positionsToAdd.isEmpty()) {
                        // 如果有新的职位，并且 positions 长度未超过 1000，添加到现有的行业中
                        Update update = new Update().addToSet("positions").each(positionsToAdd.toArray());
                        mongoTemplate.updateFirst(new Query(Criteria.where("name").is(industry.getName())), update, Industry.class);
                    }
                }  
                // 如果 positions 长度已达到或超过 1000，跳过更新
            } else {
                // 如果行业不存在，将其添加到待插入列表中
                industriesToInsert.add(industry);
            }
        }

        // 批量插入新的行业
        if (!industriesToInsert.isEmpty()) {
            try {
                mongoTemplate.insertAll(industriesToInsert);
            } catch (Exception e) {
                batchInsertIndustry(industriesToInsert);
            }
        }
    }

    @Override
    public List<Industry> getAllIndustry() {
        return mongoTemplate.findAll( Industry.class, "industry_position");
    }

    @Override
    public List<String> getAllIndustryName() {
        // 构建查询，只返回 name 字段
        Query query = new Query();
        query.fields().include("name").exclude("_id"); // 只包含 name 字段，不返回 _id 字段

        // 执行查询
        List<Industry> industries = mongoTemplate.find(query, Industry.class, "industry_position");
        if (CollUtil.isEmpty(industries)) {
            return Collections.emptyList();
        }
        return industries.stream()
                .map(Industry::getName)
                .collect(Collectors.toList());
    }
    @Override
    public List<String> getJobTitleByIndustryName(String industryName) {
        // 构建查询，只返回 positions 字段
        Query query = new Query(Criteria.where("name").is(industryName));
        query.fields().include("positions").exclude("_id"); // 只包含 positions 字段，不返回 _id 字段

        // 执行查询
        Industry industry = mongoTemplate.findOne(query, Industry.class, "industry_position");
        if (industry == null) {
            return Collections.emptyList();
        }
        return industry.getPositions();
    }
}
